package org.rcloud.io.Utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * Created by Administrator on 2019/3/6.
 */
@RestController
@RequestMapping(value = "/SendSms")
public class AliDayunSms {

    @RequestMapping(value = "/DuanXin", produces = {"application/json;charset=UTF-8"})
    public String sendsms(@RequestBody String params) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAIPVPuI4dD2BCQ", "xHtsCdTUYw7HYs8OaS2lTwq6HL54fI");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", params+"");
        request.putQueryParameter("SignName", " 味道山乡");
        request.putQueryParameter("TemplateCode", "120756833");
        String msgCode = getMsgCode();
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + msgCode + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getData();
        } catch (ServerException e) {
            e.printStackTrace();
            return e.toString();
        } catch (ClientException e) {
            e.printStackTrace();
            return e.toString();
        }
    }
    private static String getMsgCode() {
        int n = 6;
        StringBuilder code = new StringBuilder();
        Random ran = new Random();
        for (int i = 0; i < n; i++) {
            code.append(Integer.valueOf(ran.nextInt(10)).toString());
        }
        return code.toString();
    }
}
